using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Reflection;

namespace Q.Framework.Extension
{
	/// <summary>
	/// Sort extension methods for <c>IQueryable</c>
	/// </summary>
	public static partial class ExpressionExtension
	{
		public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string property)
		{
			return ApplyOrder<T>(source, property, "OrderBy");
		}

		public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string property)
		{
			return ApplyOrder<T>(source, property, "OrderByDescending");
		}

		public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string property)
		{
			return ApplyOrder<T>(source, property, "ThenBy");
		}

		public static IOrderedQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> source, string property)
		{
			return ApplyOrder<T>(source, property, "ThenByDescending");
		}

		static IOrderedQueryable<T> ApplyOrder<T>(IQueryable<T> source, string property, string methodName)
		{
			string[] props = property.Split('.');
            var lista = props.ToList();
            lista.RemoveAt(0);
            props = lista.ToArray();

			Type type = typeof(T);
			ParameterExpression arg = Expression.Parameter(type, "x");
			Expression expr = arg;
			foreach(string prop in props)
			{
				// use reflection (not ComponentModel) to mirror LINQ
				PropertyInfo pi = type.GetProperty(prop.Trim());
				expr = Expression.Property(expr, pi);
				type = pi.PropertyType;
			}
			Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
			LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);

			object result = typeof(Queryable).GetMethods().Single(
					method => method.Name == methodName
							&& method.IsGenericMethodDefinition
							&& method.GetGenericArguments().Length == 2
							&& method.GetParameters().Length == 2)
					.MakeGenericMethod(typeof(T), type)
					.Invoke(null, new object[] { source, lambda });

			return (IOrderedQueryable<T>) result;
		}

        public static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> source, string property)
		{
			return ApplyOrder<T>(source, property, "OrderBy");
		}

        public static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> source, string property)
		{
			return ApplyOrder<T>(source, property, "OrderByDescending");
		}

        public static IOrderedEnumerable<T> ThenBy<T>(this IEnumerable<T> source, string property)
		{
			return ApplyOrder<T>(source, property, "ThenBy");
		}

        public static IOrderedEnumerable<T> ThenByDescending<T>(this IEnumerable<T> source, string property)
		{
			return ApplyOrder<T>(source, property, "ThenByDescending");
		}

        static IOrderedEnumerable<T> ApplyOrder<T>(IEnumerable<T> source, string property, string methodName)
        {
            string[] props = property.Split('.');
            var lista = props.ToList();
            props = lista.ToArray();

            Type type = typeof(T);
            ParameterExpression arg = Expression.Parameter(type, "x");
            Expression expr = arg;
            foreach (string prop in props)
            {
                // use reflection (not ComponentModel) to mirror LINQ
                PropertyInfo pi = type.GetProperty(prop.Trim());
                expr = Expression.Property(expr, pi);
                type = pi.PropertyType;
            }
            Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
            LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);

            object result = typeof(Queryable).GetMethods().Single(
                    method => method.Name == methodName
                            && method.IsGenericMethodDefinition
                            && method.GetGenericArguments().Length == 2
                            && method.GetParameters().Length == 2)
                    .MakeGenericMethod(typeof(T), type)
                    .Invoke(null, new object[] { source, lambda });

            return (IOrderedEnumerable<T>)result;
        } 
	}
}